<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Jul 17, 2008
 * 
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );
RCoreImporter::cls( "html.HtmlControl" );

class HtmlAutocompleteControl extends HtmlControl {
	var $_formName;
	var $_action;
	var $_defaultValue;
	
	function __construct($name, $action, $formName = 'systemForm') {
		$this->_inputName = $name;
		$this->_action = $action;
		$this->_formName = $formName;
	}
	
	function createInputHtml($defaultValue = "") {
		$this->_defaultValue = $defaultValue;
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/jquery.bgiframe.min.js" );
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/jquery.autocomplete.min.js" );
		$script = "
				$().ready(function() {

				function findValueCallback(event, data, formatted) {
					var input = document.createElement(\"input\");
						input.setAttribute(\"type\", \"hidden\");
						input.setAttribute(\"name\", \"{$this->_inputName}[]\");
						input.setAttribute(\"value\", formatted);
						document.getElementById(\"{$this->_formName}\").appendChild(input);
				}
				
				function formatItem(row) {
					return \" <strong>\" + row + \"</strong>\";
				}
				function formatResult(row) {
					return row;
				}
				
				$(\"#{$this->_inputName}\").autocomplete('{$this->_action}', {
					width: 150,
					multiple: true,
					matchContains: true,
					formatItem: formatItem,
					formatResult: formatResult
				});
				
//				$(\"#{$this->_inputName}:text, textarea\").result(findValueCallback).next().click(function() {
//					$(this).prev().search();
//				});
				
				$(\"#{$this->_inputName}\").result(function(event, data, formatted) {
					var hidden = $(this).parent().next().find(\">:input\");
					hidden.val( (hidden.val() ? hidden.val() + \";\" : hidden.val())+data[1]);
				});
			});";
		SysResponse::addJavascriptContent ( $script );
		$output = "";
		$output .= "<input type=\"text\" id=\"{$this->_inputName}\" name=\"{$this->_inputName}\" value=\"{$this->_defaultValue}\"/>";
		return $output;
	}
	
	function printInputHtml($defaultValue = "") {
		echo $this->createInputHtml ( $defaultValue );
	}
	
	function getSearchKey() {
		return $_GET ['q'];
	}
}

?>